<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
        //实例化数据库
        $page = D("page");
        $ss = D("user");
        $comment = D("comment");
        $school=D("yitao_school");


      // 默认未登录用户ID为0
      if(!session("id")){
        session("id",0);
      }
        


        //获取session值
        $session_id = session('id');
        if(!empty($_COOKIE["user"]) && !empty($_COOKIE["pass"])){
            $where = array(
                    'user' => cookie("user"),
                    'pass' => cookie("pass"),
                );
                $is = $ss->where($where)->find();
                $session_id = $is["id"];
        }
        //获取用户名送往前端 如果session_id大于1获取用户的学校id否则学校id为0显示设定好的留言
        if($session_id > 1) {
            // echo "4";die();
            $is = $ss->where("id=$session_id")->find();
            $this->assign("is", $is);

            $sid = $is['sid'];
            session('sid',$sid);//学校ID
        }else{
            session('sid',0);//学校ID

            $sid = "0";
        }

        // 保存学校ID
        
        $uer_school=$school->where(array("id"=>$sid))->select();

        session('school',$uer_school[0]['name']);//学校名
        

        $this->assign("school",$uer_school[0]['name']);
        
        $this->assign("session_id",$session_id);
        //根据用户的学校id遍历出本校的表白信息
        $contents = $page->order('id DESC')->where(array('sid' => $sid))->limit(4)->select();

        
        // var_dump($contents);die();
        //数据写入数据库并发往前端循环
        $data = array();
        $data['contents'] = $contents;
        $this->assign("data",$data);


        // 判断显示个人中心还是登陆
        $flag=false;

        if($session_id){
            // echo $session_id;die();
            $flag=true;
        }
        session("flag",$flag);
        // echo $flag;die();
         $this->assign("flag",$flag);
        // 判断显示个人中心还是登陆结束

         // 头像
        $userId=session("id");
        $ss = D("user");
        $userInfo=$ss->where(array('id'=>$session_id))->select();
        $url='http://'.$_SERVER['HTTP_HOST'].substr($PHP_SELF,0,strrpos($PHP_SELF,'/')+1);
        $url2=substr($userInfo[0]['userimage'],strrpos($userInfo[0]['userimage'],"clientFile"));    
        $headImgSrc=$url.__ROOT__.'/'.$url2;
        // echo $headImgSrc;die();
        session("headImgSrc",$headImgSrc);
        $this->headImgSrc=$headImgSrc;
          //头像结束
        $this->display();
    }


    public function comment(){
        //实例化数据库
        $page = D("page");
        $comment = D("comment");
        $ss = D("user");
        //获取前端数据
        $pid = I("get.pid");

        //遍历用户留言数据表
        $content = $page->where("id=$pid")->find();

        $this->assign("content",$content);

        //获取session值
        $session_id = session('id');

        if(IS_POST) {
            //接收前端数据
            $comm = I("post.comment");
            if ($session_id > 1) {
                $user_data = $ss->where("id=$session_id")->find();

                $comment_data = array(
                    "pid" => $pid,
                    "user" => $user_data['user'],
                    "ssid" => $user_data['ssid'],
                    'comm' => $comm,
                );
                $comment->add($comment_data);
            }else{
                return $this->error("请登录后评论", U("Home/Login/index"));
            }
        }
        if($pid > 1) {
            $comment_datas = $comment->where("pid=$pid")->select();
            $this->assign("comment_datas", $comment_datas);
        }
        $this->display();
    }

    //查看留言
    public function get_comment(){
        if(!empty($_GET)){
            $id = I('get.id');
            $comment_info = D('comment')->where("pid = $id")->select();
            $this->ajaxReturn($comment_info);
        }
        if(!empty($_POST)){
            $session_id = session('id');
            if ($session_id > 1) {
                $user_data = D('user')->where("id=$session_id")->find();

                $comment_data = array(
                    "pid" => I('post.id'),
                    "user" => $user_data['user'],
                    "ssid" => $user_data['ssid'],
                    'comm' => I('post.content'),
                );
                $result = M('comment')->add($comment_data);
                if($result){
                    $re['error'] = 0;
                    $this->ajaxReturn($comment_data);
                }
            }else{
                $re['error'] = 1;
                $re['msg'] = '请登录后评论';
                $this->ajaxReturn($re);
            }
        }
    }

    public function praise(){
        $do = I("get.do");

        if($do == "chk"){

        }
        $this->display();
    }
    public function add(){
        //实例化用户发表留言的数据库
        $page = D("page");
        $ss = D("user");

        //获取前端参数
        $id = session('id');
        $user = session('user');
        $content = $_POST["content"];
        $content_to = I("post.content_to");
        $intime = time();
        $userdb = $ss->where("id=$id")->find();
        $sid=$userdb["sid"];
        // echo $sid;die();
        //如果id值小于1说明没有登录,跳转到登录页
        if($id < 1){
            return $this->redirect("Home/Login/index");
        }
        /*
         * 利用用户登录的session值在用户数据库里找到这个用户，然后把这个用户的ssid（昵称）找出来，写进文章里
         * 在主页显示的是用户的昵称
         */
        

        //把数据写进数据库
        if(IS_POST){
            $write = array(
                'ssid'=> $userdb['ssid'],
                // 'sid'=>$userdb['sid'],
                'user' => $user,
                'content'=> $content,
                'intime' => $intime,
                'content_to'=>$content_to,
                'sid'=>$sid,
            );
            //判断留言内容是否为空
            if(empty($content)){
                return $this->error("留言内容不能为空", U("Home/Index/add"));
            }
            $is = $page->add($write);
            //如果写入成功跳回主页，写入失败报错
            if($is){
                return $this->redirect("Home/Index/index");
            }else{
                return $this->error("帐号或密码错误", U("Home/Index/add"));
            }
        }
        $this->display();
    }
    //赞
    public function laud(){
        if(!empty($_POST)){
            $id = I('post.id');
            $type = I('post.type');
            if($type == 1){
                $sql = 'update page set laud = laud + 1 where id = '.$id;
            }
            if($type == 2){
                $sql = 'update page set laud = laud - 1 where id = '.$id;
            }
            M()->query($sql);
        }
    }


    //单独显示
     public function singleSay(){
        // echo $_GET["pid"];die();
        if($_GET["pid"]){
            $pid=$_GET["pid"];
            $page=M("page");

            $res=$page->where(array('id'=>$pid))->select();
            
            if(session("id")){
                 $this->assign("school",session("school"));
                 $this->assign("headImgSrc",session("headImgSrc"));

            }
            $this->assign("flag",session("flag"));
            $this->assign("page",$res[0]);
            // echo session("id");die();
            $this->assign("uid",session("id"));


            // 获取评论
            $comment=M("comment")->join("left join user ON comment.uid = user.id")->where(array("pid"=>$pid))->order('initime DESC')->select();//根据pid获取评论
            // $comments=D("CommentRelation")->relation(true)->select();
            // var_dump($comments);die;
            // $sql="select * from comment left join user on comment.uid = user.id ";
            // $comments=M()->query($sql);
            // var_dump($comment);die();
            $this->assign("comment",$comment);



            // 获取评论结束


            $this->display();
        }
        
    }

     //瀑布流增加数据
     public function wookmarkAdd(){
        // $id=$_POST["id"];    
        if(IS_AJAX){ 
            $uid=session('id');//用户ID
            $sid=session('sid');//用户学校ID
            $current_count=$_POST['current_count'];//当前li数量
            $page=D("page");
            $contents = $page->order('id DESC')->where(array('sid' => $sid))->limit($current_count,1)->select();

            // var_dump($contents);die();

            $str='';

            

            for($i=0;$i<count($contents);$i++){

               $str.='<li onClick=\'location.href="'.U('/Home/Index/singleSay',array('pid'=>$contents[$i]["id"])).'";\'>'.'<!-- <img src="images/img1.jpg" width="200" height="200"> -->

                              
                                <div class="post-info">

                                    
                                    <div class="post-header-info">

                                        <h3 class="to">TO :'.$contents[$i]["content_to"].'</h3>

                                        <h4 class="time">'.date('Y-m-d H:i:s',"$contents[$i]['initime']").'</h4>

                                    </div>   
                                                                  
                                    <div class="post-basic-info">
                                        <!-- <h3><a href="#">Animation films</a></h3> -->
                                        <!-- <span><a href="#"><label> </label>Movies</a></span> -->
                                        <p>'.$contents[$i]["content"].'</p>

                                        <h3 class="from">Form: '.$contents[$i]["ssid"].'</h3>
                                    </div>                             
                                    <div class="post-info-rate-share">

                                        <p>
                                            <a href="javascript:;" class="laud" name="'.$contents[$i]["id"].'" type="1"> 点赞(<span>'.$contents[$i]["laud"].'</span>)</a>
                                                                      
                                        </p>

                                        <div class="clear"> </div>
                                    </div>
                                    
                                </div>
                                
                            </li>';

            }
            $this->ajaxReturn($str);
        }
        
    }


    // 单页增加评论
     public function addComment(){
        if(IS_AJAX){
            if($_POST['type']==1){
                    $pid=$_POST["pid"];
                    $uid=session("id");
                   
                    $com=$_POST["com"];

                    $data=array(
                        "pid"=>$pid,
                        "uid"=>$uid,
                        "initime"=>time(),
                        "comm"=>$com,

                        );
                    $res=M("comment")->add($data);
                    if($res){
                        $this->ajaxReturn("success");
                    }
            }elseif($_POST['type']==2){
                $loginId=$_POST['loginId'];
                $pid=$_POST['pid'];
                $reply_to_id=$_POST['reply_to_id'];
                $comm=$_POST['comm'];
                $data=array(
                        "pid"=>$pid,
                        "uid"=>$loginId,
                        "initime"=>time(),
                        "comm"=>$comm,
                        "reply_to_id"=>$reply_to_id,
                        );
                $res=M("comment")->add($data);
                if($res){
                    $this->ajaxReturn("success");
                }

            }else{
                 $this->ajaxReturn("fail");
            }
        }
     }

}